--- title: "三羊献瑞" created: 2025-11-28 tags: - 算法 --- # 三羊献瑞 ## 题目 [三羊献瑞](https://www.lanqiao.cn/problems/674/learning/) ![[image-2a63d8ca.png]] ## 思路分析 这道题刷真题卷的时候用的是纯暴力把每个数都套1~9 代码极其夸张 三羊献瑞 其实可以套用上一题的思路 因为每个字都在0~9之间 且不重复 所以可以先做出全排列 再想办法套给每个字 ![[image-d0bb2f6c.png]] ## 代码实现 ```cpp #include using namespace std; const int N=10; int alls[N]; bool st[N]; int ans; void dfs(int u){ if(u==9){ int A=alls[0]*1000+alls[1]*100+alls[2]*10+alls[3]; int B=alls[4]*1000+alls[5]*100+alls[6]*10+alls[1]; int C=alls[4]*10000+alls[5]*1000+alls[2]*100+alls[1]*10+alls[7]; if(A+B==C && B>1000) ans=B; return; } for(int i=0;i<=9;i++){ if(!st[i]){ st[i]=true; alls[u]=i; dfs(u+1); alls[u]=0; st[i]=false; } } } int main() { dfs(0); cout< using namespace std; vector alls={0,1,2,3,4,5,6,7,8,9}; int main() { do{ int A=alls[0]*1000+alls[1]*100+alls[2]*10+alls[3]; int B=alls[4]*1000+alls[5]*100+alls[6]*10+alls[1]; int C=alls[4]*10000+alls[5]*1000+alls[2]*100+alls[1]*10+alls[7]; if(A+B==C && B>1000){ cout<